﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.CMS.Content;

namespace MethodWorx.CMS.TemplateParser
{
    /// <summary>
    /// Simple parent child template hierarchy derived from a leaf template
    /// </summary>
    public class TemplateHierarchy : IEnumerable<PageTemplate>
    {
        private List<PageTemplate> templateHierarchy = new List<PageTemplate>();

        public TemplateHierarchy(PageTemplate leafTemplate)
        {
            while(leafTemplate.Parent != null)
            {
                templateHierarchy.Add(leafTemplate);
                leafTemplate = leafTemplate.Parent;
            }
            templateHierarchy.Add(leafTemplate);
        }

        /// <summary>
        /// Get the child of the parent template
        /// </summary>
        /// <param name="parent"></param>
        /// <returns></returns>
        public PageTemplate GetChild(PageTemplate parent)
        {
            foreach(var child in templateHierarchy)
            {
                if (child.Parent == parent)
                    return child;
            }

            return null;
        }

        /// <summary>
        /// Get the root template
        /// </summary>
        /// <returns></returns>
        public PageTemplate GetRootTemplate()
        {
            return this.templateHierarchy.FirstOrDefault(t => t.Parent == null);
        }

        public IEnumerator<PageTemplate> GetEnumerator()
        {
            return this.templateHierarchy.AsReadOnly().Reverse().GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.templateHierarchy.AsReadOnly().Reverse().GetEnumerator();
        }
    }
}
